from farstyle.filters import FilterBase
from farstyle import settings

import os
import subprocess
import tempfile

binary = getattr(settings, 'LESS_BINARY')

class LESSFilter(FilterBase):
    def filter_css(self, css):
        infile = tempfile.NamedTemporaryFile()
        infile.write(css)
        infile.seek(0)
        tmp, tmp_name = tempfile.mkstemp()
        os.close(tmp)

        params = [binary, infile.name, tmp_name]
        if settings.DEBUG:
            params.append('--debug')
        process = subprocess.Popen(params,
            stdin=subprocess.PIPE, stderr=subprocess.PIPE)
        stdoutdata, stderrdata = process.communicate(css)
        infile.close()

        if stderrdata:
            if settings.DEBUG:
                os.unlink(tmp_name)
                raise ValueError, stderrdata
            filtered_css = u''
        else:
            f = open(tmp_name, 'r')
            filtered_css = f.read()
            f.close()

        os.unlink(tmp_name)
        return filtered_css
